{% extends "base.html" %}

{% block title %}修改预约 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}修改预约{% endblock %}

{% block extra_css %}
<style>
    .edit-container {
        max-width: 700px;
        margin: 0 auto;
    }

    .current-info {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 12px;
        padding: 25px;
        margin-bottom: 30px;
    }

    .current-info h5 {
        margin-bottom: 20px;
        display: flex;
        align-items: center;
    }

    .current-info i {
        margin-right: 10px;
    }

    .info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
    }

    .info-item {
        background: rgba(255,255,255,0.1);
        border-radius: 8px;
        padding: 15px;
        text-align: center;
    }

    .info-label {
        font-size: 0.9rem;
        opacity: 0.8;
        margin-bottom: 5px;
    }

    .info-value {
        font-weight: 600;
        font-size: 1.1rem;
    }

    .edit-form {
        background: white;
        border-radius: 12px;
        padding: 30px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .form-section {
        margin-bottom: 25px;
    }

    .section-title {
        font-weight: 600;
        color: #495057;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
    }

    .section-title i {
        margin-right: 10px;
        color: #007bff;
    }

    .time-slots {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
        gap: 10px;
        margin-top: 15px;
    }

    .time-slot {
        border: 1px solid #dee2e6;
        border-radius: 6px;
        padding: 8px 4px;
        text-align: center;
        cursor: pointer;
        transition: all 0.2s ease;
        font-size: 0.9rem;
    }

    .time-slot:hover {
        border-color: #007bff;
        background: #f8f9ff;
    }

    .time-slot.selected {
        background: #007bff;
        color: white;
        border-color: #007bff;
    }

    .time-slot.disabled {
        background: #f8f9fa;
        color: #6c757d;
        cursor: not-allowed;
        border-color: #e9ecef;
    }

    .table-option {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 10px;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .table-option:hover {
        border-color: #007bff;
        background: #f8f9ff;
    }

    .table-option.selected {
        border-color: #007bff;
        background: #e3f2fd;
    }

    .table-option input[type="radio"] {
        margin-right: 10px;
    }

    .warning-card {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
    }

    .warning-title {
        color: #856404;
        font-weight: 600;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
    }

    .warning-title i {
        margin-right: 10px;
    }

    .warning-content {
        color: #856404;
        font-size: 0.9rem;
        line-height: 1.5;
    }

    .changes-summary {
        background: #e3f2fd;
        border: 1px solid #bbdefb;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
    }

    .changes-title {
        color: #1976d2;
        font-weight: 600;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
    }

    .changes-title i {
        margin-right: 10px;
    }

    .change-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #e3f2fd;
    }

    .change-item:last-child {
        border-bottom: none;
    }

    .change-label {
        font-weight: 500;
        color: #1976d2;
    }

    .change-values {
        text-align: right;
    }

    .old-value {
        color: #666;
        text-decoration: line-through;
        font-size: 0.9rem;
    }

    .new-value {
        color: #1976d2;
        font-weight: 500;
    }

    .btn-save {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        border: none;
        color: white;
        padding: 12px 30px;
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.2s ease;
    }

    .btn-save:hover {
        background: linear-gradient(135deg, #20c997 0%, #28a745 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
        color: white;
    }

    .duration-display {
        background: #f8f9fa;
        border-radius: 6px;
        padding: 10px;
        text-align: center;
        margin-top: 10px;
        font-weight: 500;
        color: #495057;
    }

    .price-estimate {
        background: #fff3e0;
        border: 1px solid #ffcc02;
        border-radius: 6px;
        padding: 10px;
        margin-top: 10px;
        text-align: center;
    }

    .price-amount {
        font-size: 1.2rem;
        font-weight: bold;
        color: #f57c00;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="edit-container">
        <!-- 返回按钮 -->
        <div class="mb-3">
            <a href="{{ url_for('student_reservations.detail', reservation_id=reservation.id) }}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> 返回预约详情
            </a>
        </div>

        <!-- 当前预约信息 -->
        <div class="current-info">
            <h5>
                <i class="bi bi-pencil-square"></i>
                修改预约信息
            </h5>
            <div class="info-grid">
                <div class="info-item">
                    <div class="info-label">当前日期</div>
                    <div class="info-value">{{ reservation.reservation_date.strftime('%m月%d日') }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">当前时间</div>
                    <div class="info-value">
                        {{ reservation.start_time.strftime('%H:%M') }} - {{ reservation.end_time.strftime('%H:%M') }}
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">教练</div>
                    <div class="info-value">{{ reservation.coach.real_name }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">当前球台</div>
                    <div class="info-value">{{ reservation.table.name }}</div>
                </div>
            </div>
        </div>

        <!-- 警告信息 -->
        <div class="warning-card">
            <div class="warning-title">
                <i class="bi bi-exclamation-triangle"></i>
                修改说明
            </div>
            <div class="warning-content">
                <ul class="mb-0">
                    <li>只能修改待确认状态的预约</li>
                    <li>修改必须在课程开始前24小时进行</li>
                    <li>教练信息无法修改，如需更换教练请重新预约</li>
                    <li>修改后需要教练重新确认</li>
                </ul>
            </div>
        </div>

        <!-- 修改表单 -->
        <div class="edit-form">
            <form method="POST" id="editForm">
                {{ form.hidden_tag() }}

                <!-- 日期选择 -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="bi bi-calendar3"></i>
                        预约日期
                    </div>
                    {{ form.reservation_date(class="form-control", onchange="updateTimeSlots()") }}
                    {% if form.reservation_date.errors %}
                        <div class="text-danger small mt-1">
                            {% for error in form.reservation_date.errors %}
                                <i class="bi bi-exclamation-circle"></i> {{ error }}
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>

                <!-- 时间选择 -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="bi bi-clock"></i>
                        上课时间
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label">开始时间</label>
                            {{ form.start_time(class="form-control", onchange="updateEndTime()") }}
                            {% if form.start_time.errors %}
                                <div class="text-danger small mt-1">
                                    {% for error in form.start_time.errors %}
                                        {{ error }}
                                    {% endfor %}
                                </div>
                            {% endif %}
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">结束时间</label>
                            {{ form.end_time(class="form-control", onchange="validateTimeRange()") }}
                            {% if form.end_time.errors %}
                                <div class="text-danger small mt-1">
                                    {% for error in form.end_time.errors %}
                                        {{ error }}
                                    {% endfor %}
                                </div>
                            {% endif %}
                        </div>
                    </div>

                    <!-- 时长显示 -->
                    <div class="duration-display" id="durationDisplay">
                        请选择开始和结束时间
                    </div>

                    <!-- 快速时间选择 -->
                    <div class="mt-3">
                        <label class="form-label">快速选择时间段</label>
                        <div class="time-slots" id="timeSlots">
                            <!-- 时间段将通过JavaScript生成 -->
                        </div>
                    </div>
                </div>

                <!-- 球台选择 -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="bi bi-grid-3x3"></i>
                        选择球台
                    </div>

                    <div id="tableOptions">
                        {% for value, label in form.table_id.choices %}
                            {% if value %}
                            <div class="table-option" onclick="selectTable('{{ value }}')">
                                <input type="radio" name="table_id" value="{{ value }}" id="table_{{ value }}"
                                       {% if form.table_id.data == value %}checked{% endif %}>
                                <label for="table_{{ value }}" class="mb-0">
                                    <strong>{{ label.split(' - ')[0] }}</strong>
                                    {% if ' - ' in label %}
                                        <br><small class="text-muted">{{ label.split(' - ')[1] }}</small>
                                    {% endif %}
                                </label>
                            </div>
                            {% endif %}
                        {% endfor %}
                    </div>

                    {% if form.table_id.errors %}
                        <div class="text-danger small mt-2">
                            {% for error in form.table_id.errors %}
                                <i class="bi bi-exclamation-circle"></i> {{ error }}
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>

                <!-- 费用预估 -->
                <div class="price-estimate" id="priceEstimate" style="display: none;">
                    <div>预估费用</div>
                    <div class="price-amount" id="priceAmount">¥0.00</div>
                    <small class="text-muted">实际费用以教练确认为准</small>
                </div>
            </form>
        </div>

        <!-- 变更摘要 -->
        <div class="changes-summary" id="changesSummary" style="display: none;">
            <div class="changes-title">
                <i class="bi bi-arrow-repeat"></i>
                变更摘要
            </div>
            <div id="changesContent">
                <!-- 变更内容将通过JavaScript填充 -->
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="text-center">
            <a href="{{ url_for('student_reservations.detail', reservation_id=reservation.id) }}"
               class="btn btn-outline-secondary btn-lg me-3">
                <i class="bi bi-x"></i> 取消修改
            </a>
            <button type="submit" form="editForm" class="btn btn-save btn-lg" id="saveBtn">
                <i class="bi bi-check-circle"></i> 保存修改
            </button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 原始数据
const originalData = {
    date: '{{ reservation.reservation_date.isoformat() }}',
    startTime: '{{ reservation.start_time.strftime("%H:%M") }}',
    endTime: '{{ reservation.end_time.strftime("%H:%M") }}',
    tableId: '{{ reservation.table_id }}'
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    generateTimeSlots();
    updateDurationDisplay();
    updateTableSelection();
    checkChanges();

    // 设置最小日期为今天
    const today = new Date().toISOString().split('T')[0];
    document.querySelector('#reservation_date').setAttribute('min', today);
});

// 生成时间段选择
function generateTimeSlots() {
    const timeSlotsContainer = document.getElementById('timeSlots');
    const slots = [];

    // 生成8:00-22:00的时间段，每30分钟一个
    for (let hour = 8; hour < 22; hour++) {
        for (let minute = 0; minute < 60; minute += 30) {
            const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
            slots.push(timeStr);
        }
    }

    timeSlotsContainer.innerHTML = '';
    slots.forEach(time => {
        const slot = document.createElement('div');
        slot.className = 'time-slot';
        slot.textContent = time;
        slot.onclick = () => selectTimeSlot(time);
        timeSlotsContainer.appendChild(slot);
    });
}

// 选择时间段
function selectTimeSlot(startTime) {
    document.getElementById('start_time').value = startTime;

    // 自动设置结束时间（默认1小时）
    const [hours, minutes] = startTime.split(':').map(Number);
    const startDate = new Date();
    startDate.setHours(hours, minutes, 0);

    const endDate = new Date(startDate.getTime() + 60 * 60000); // 加1小时
    const endTimeStr = `${endDate.getHours().toString().padStart(2, '0')}:${endDate.getMinutes().toString().padStart(2, '0')}`;

    if (endDate.getHours() <= 22) {
        document.getElementById('end_time').value = endTimeStr;
    }

    updateDurationDisplay();
    checkChanges();
}

// 更新结束时间
function updateEndTime() {
    updateDurationDisplay();
    checkChanges();
}

// 验证时间范围
function validateTimeRange() {
    updateDurationDisplay();
    checkChanges();
}

// 更新时长显示
function updateDurationDisplay() {
    const startTime = document.getElementById('start_time').value;
    const endTime = document.getElementById('end_time').value;
    const display = document.getElementById('durationDisplay');

    if (!startTime || !endTime) {
        display.textContent = '请选择开始和结束时间';
        display.className = 'duration-display';
        return;
    }

    const [startHour, startMin] = startTime.split(':').map(Number);
    const [endHour, endMin] = endTime.split(':').map(Number);

    const startMinutes = startHour * 60 + startMin;
    const endMinutes = endHour * 60 + endMin;
    const durationMinutes = endMinutes - startMinutes;

    if (durationMinutes <= 0) {
        display.textContent = '结束时间必须晚于开始时间';
        display.className = 'duration-display text-danger';
        return;
    }

    if (durationMinutes < 30) {
        display.textContent = '课程时长不能少于30分钟';
        display.className = 'duration-display text-warning';
        return;
    }

    if (durationMinutes > 240) {
        display.textContent = '课程时长不能超过4小时';
        display.className = 'duration-display text-warning';
        return;
    }

    const hours = Math.floor(durationMinutes / 60);
    const minutes = durationMinutes % 60;
    let durationText = '';

    if (hours > 0) {
        durationText += `${hours}小时`;
    }
    if (minutes > 0) {
        durationText += `${minutes}分钟`;
    }

    display.textContent = `课程时长：${durationText}`;
    display.className = 'duration-display text-success';

    // 更新价格预估
    updatePriceEstimate(durationMinutes);
}

// 更新价格预估
function updatePriceEstimate(durationMinutes) {
    if (durationMinutes >= 30 && durationMinutes <= 240) {
        const hourlyRate = 100; // 假设基础价格100元/小时
        const hours = durationMinutes / 60;
        const estimatedPrice = hourlyRate * hours;

        document.getElementById('priceAmount').textContent = `¥${estimatedPrice.toFixed(2)}`;
        document.getElementById('priceEstimate').style.display = 'block';
    } else {
        document.getElementById('priceEstimate').style.display = 'none';
    }
}

// 选择球台
function selectTable(tableId) {
    // 清除之前的选择
    document.querySelectorAll('.table-option').forEach(option => {
        option.classList.remove('selected');
    });

    // 选择当前球台
    const selectedOption = document.querySelector(`input[value="${tableId}"]`).closest('.table-option');
    selectedOption.classList.add('selected');

    // 设置radio状态
    document.querySelector(`input[value="${tableId}"]`).checked = true;

    checkChanges();
}

// 更新球台选择状态
function updateTableSelection() {
    const selectedRadio = document.querySelector('input[name="table_id"]:checked');
    if (selectedRadio) {
        selectTable(selectedRadio.value);
    }
}

// 检查变更
function checkChanges() {
    const currentData = {
        date: document.getElementById('reservation_date').value,
        startTime: document.getElementById('start_time').value,
        endTime: document.getElementById('end_time').value,
        tableId: document.querySelector('input[name="table_id"]:checked')?.value || ''
    };

    const hasChanges = Object.keys(originalData).some(key =>
        originalData[key] !== currentData[key]
    );

    // 显示/隐藏变更摘要
    const summaryDiv = document.getElementById('changesSummary');
    if (hasChanges) {
        summaryDiv.style.display = 'block';
        updateChangesSummary(currentData);
    } else {
        summaryDiv.style.display = 'none';
    }

    // 启用/禁用保存按钮
    document.getElementById('saveBtn').disabled = !hasChanges;
}

// 更新变更摘要
function updateChangesSummary(currentData) {
    const changesContent = document.getElementById('changesContent');
    let changesHtml = '';

    // 检查日期变更
    if (originalData.date !== currentData.date) {
        const oldDate = new Date(originalData.date);
        const newDate = new Date(currentData.date);
        changesHtml += `
            <div class="change-item">
                <div class="change-label">预约日期</div>
                <div class="change-values">
                    <div class="old-value">${oldDate.getMonth() + 1}月${oldDate.getDate()}日</div>
                    <div class="new-value">${newDate.getMonth() + 1}月${newDate.getDate()}日</div>
                </div>
            </div>
        `;
    }

    // 检查时间变更
    if (originalData.startTime !== currentData.startTime || originalData.endTime !== currentData.endTime) {
        changesHtml += `
            <div class="change-item">
                <div class="change-label">上课时间</div>
                <div class="change-values">
                    <div class="old-value">${originalData.startTime} - ${originalData.endTime}</div>
                    <div class="new-value">${currentData.startTime} - ${currentData.endTime}</div>
                </div>
            </div>
        `;
    }

    // 检查球台变更
    if (originalData.tableId !== currentData.tableId) {
        const oldTableLabel = document.querySelector(`input[value="${originalData.tableId}"]`)?.closest('.table-option')?.querySelector('strong')?.textContent || '原球台';
        const newTableLabel = document.querySelector(`input[value="${currentData.tableId}"]`)?.closest('.table-option')?.querySelector('strong')?.textContent || '新球台';

        changesHtml += `
            <div class="change-item">
                <div class="change-label">球台</div>
                <div class="change-values">
                    <div class="old-value">${oldTableLabel}</div>
                    <div class="new-value">${newTableLabel}</div>
                </div>
            </div>
        `;
    }

    changesContent.innerHTML = changesHtml;
}

// 监听表单字段变化
document.getElementById('reservation_date').addEventListener('change', checkChanges);
document.getElementById('start_time').addEventListener('change', checkChanges);
document.getElementById('end_time').addEventListener('change', checkChanges);

// 监听球台选择变化
document.querySelectorAll('input[name="table_id"]').forEach(radio => {
    radio.addEventListener('change', checkChanges);
});

// 为所有球台选项添加点击事件
document.querySelectorAll('.table-option').forEach(option => {
    option.addEventListener('click', function() {
        const radio = this.querySelector('input[type="radio"]');
        if (radio) {
            selectTable(radio.value);
        }
    });
});

// 阻止点击radio时的事件冒泡
document.querySelectorAll('.table-option input[type="radio"]').forEach(radio => {
    radio.addEventListener('click', function(e) {
        e.stopPropagation();
        selectTable(this.value);
    });
});
</script>
{% endblock %}